<style lang="less" scoped>
// /deep/.el-scrollbar__bar.is-horizontal{
//   height: 15px;
// }
/* 进度条遮罩 */
.progress-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.6); /* 半透明黑色背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999; /* 确保遮罩在最前面 */
}

/* 进度条样式 */
.progress-bar {
  width: 400px;
  background-color: #fff; /* 进度条背景白色 */
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.3);
}
.hy-point {
  width: 100%;
  height: 100%;
  .shaixuan {
    display: flex;
    align-items: center;
    justify-content: end;
    background: #fff;
    padding: 5px;
    img {
      height: 20px;
    }
  }
  /deep/.el-table__inner-wrapper {
    height: 100% !important;
  }
  .pagination-css {
    padding: 5px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    justify-content: right;
    margin-top: 5px;
  }
  /deep/.info{
    .el-dialog__body{
      height: 150px;
    }
  }
}
/deep/.el-dialog__body{
  height: 570px;
  overflow-y: auto;
}
</style>

<template>
  <div class="hy-point">
    <el-form
      :inline="true"
      :model="formInline"
      class="demo-form-inline form-css"
    >
      <el-form-item label="关键字：">
        <el-input
          v-model="formInline.keyword"
          placeholder="请输入条码、姓名、设备名称"
        />
      </el-form-item>
      <el-form-item label="检查时间：">
        <el-date-picker
          v-model="formInline.inspectionTime"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item label="报告时间：">
        <el-date-picker
          v-model="formInline.reportTime"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item label="质控日期：">
        <el-date-picker
          v-model="formInline.qualityTime"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item label="项目点名称：">
        <el-select
          v-model="formInline.projectName"
          placeholder="请输入项目点名称"
          filterable
        >
          <el-option
            v-for="(item, index) in organNameList"
            :key="index"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="检查医师：">
        <el-input
          v-model="formInline.inspectDoctor"
          placeholder="请输入检查医师"
        />
      </el-form-item>
      <el-form-item label="报告医师：">
        <el-input
          v-model="formInline.reportDoctor"
          placeholder="请输入报告医师"
        />
      </el-form-item>
      <el-form-item label="报告状态：">
        <el-select v-model="formInline.reportStatus" placeholder="请选择">
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否有效：">
        <el-select v-model="formInline.isInvalid" placeholder="请选择">
          <el-option
            v-for="item in isUsedList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="诊断结论：">
        <el-input v-model="formInline.diagnosis" placeholder="" />
      </el-form-item>
      <el-form-item label="是否阳性：">
        <el-select v-model="formInline.isPositive" placeholder="请选择">
          <el-option
            v-for="item in isPositiveList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" style="display: flex; align-items: center; flex-wrap: nowrap;width: 100%;">
        <el-button type="primary" @click="search"><el-icon style="margin-right: 6px"><Search /></el-icon>搜索</el-button>
        <el-button @click="reset"><el-icon style="margin-right: 6px"><Refresh /></el-icon>重置</el-button>
        <vue3-json-excel
          v-if="roleInfo != 13"
          :fields="json_fields"
          :name="userExcelName"
          :fetch="downloadEx"
          style="margin-left: 12px"
        >
          <el-button>
            <!-- <el-icon style="margin-right: 6px"><Document /></el-icon> -->
            <img
              style="margin-right: 6px; width: 12px"
              src="@/images/daochu.png"
              alt="导出患者信息"
            />

            批量导出信息</el-button
          >
        </vue3-json-excel>
        <!-- <el-button type="primary"><el-icon><Document /></el-icon>导出</el-button> -->
        <el-button
          type="primary"
          :disabled="selectedItems.length === 0"
          style="margin-left: 12px"
          :style="{backgroundColor: selectedItems.length > 0 ? '#409EFF' : '#C0C4CC' }"
          @click="exportSelectedPDFs"
        >
        导出已选定的报告
        </el-button>
        <!-- 新增的批量导出全部报告按钮 -->
        <el-button type="primary" style="margin-left: 12px" @click="exportAllPDFs">
          批量导出全部报告
        </el-button>
       <!-- 进度条背景遮罩 -->
    <div v-if="progressVisible" class="progress-mask">
      <el-progress 
        :percentage="progress" 
        :status="progressStatus"
        :text-inside="true"
        stroke-width="30"
        :format="progressFormat"
        class="progress-bar"
      />
    </div>
      </el-form-item>
    </el-form>
    <div class="filter-column">
      <el-popover
        placement="bottom"
        title="筛选条件"
        :width="150"
        trigger="click"
      >
        <el-checkbox-group v-model="filtrateList" @change="changeBox">
          <!-- <el-checkbox label="t_sn">条码</el-checkbox> -->
          <el-checkbox label="insname">项目点名称</el-checkbox>
          <el-checkbox label="name">姓名</el-checkbox>
          <el-checkbox label="sex">性别</el-checkbox>
          <el-checkbox label="age">年龄</el-checkbox>
          <el-checkbox label="tel">联系电话</el-checkbox>
          <el-checkbox label="isPositive">是否阳性</el-checkbox>
          <el-checkbox label="diagnostic">诊断结论</el-checkbox>
          <el-checkbox label="isInvalid">是否有效</el-checkbox>
          <el-checkbox label="invalidReason">无效原因</el-checkbox>
          <el-checkbox label="devname">设备名称</el-checkbox>
          <el-checkbox label="auditstatus">报告状态</el-checkbox>
          <el-checkbox label="dicomurl">常规报告</el-checkbox>
          <el-checkbox label="checkTime">检查时间</el-checkbox>
          <el-checkbox label="docname">检查医师</el-checkbox>
          <el-checkbox label="reportTime">报告时间</el-checkbox>
          <el-checkbox label="reportDoctor">报告医师</el-checkbox>
          <el-checkbox label="qualityTime">质控日期</el-checkbox>
          <el-checkbox label="medicalRecordID">病历记录ID</el-checkbox>
          <el-checkbox label="devid">设备SN</el-checkbox>
        </el-checkbox-group>
        <template #reference>
          <el-button type="text"
            ><div class="shaixuan">
              <img src="@/images/shaixuan.png" alt="" /> 筛选列
            </div></el-button
          >
        </template>
      </el-popover>
    </div>
    <el-table
      v-loading="tableLoading"
      :data="tableData"
      :header-cell-style="{ backgroundColor: '#EEF6FF' }"
      stripe
      border
      height="calc(100% - 373px)"
      class="table-css"
      style="width: 100%; padding: 10px"
      @selection-change="handleSelectionChange"   
    >
    <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" width="50" align="center" />
      <el-table-column
        prop="t_sn"
        min-width="120px"
        label="条码"
        align="center"
        show-overflow-tooltip
      />
      <!-- <el-table-column
        v-if="filtrateList.includes('insname') && $store.getters.name == 'admin'"
        prop="insname"
        min-width="200px"
        label="项目点名称"
        align="center"
      >
        <template #default="scoped">
          <div v-if="!scoped.row.isEdit" @click="choseInsname(scoped.row, scoped.$index)" :style="{color: '#409eff', width: '175px', height: scoped.row.insname ? '100%' : '23px'}">{{ scoped.row.insname }}</div>
          <div v-else style="display: flex; align-items: center;">
            <el-select v-model="scoped.row.insname1" filterable placeholder="">
              <el-option v-for="(item, index) in projectList" :key="index" :label="item.insname" :value="item.insname" />
            </el-select>
            <span @click="submitInsname(scoped.row, scoped.$index)"><el-icon><Check /></el-icon></span>
            <span @click="scoped.row.isEdit = false"><el-icon><Close /></el-icon></span>
          </div>
        </template>
      </el-table-column> -->
      <el-table-column
        v-if="filtrateList.includes('insname')"
        prop="insname"
        min-width="200px"
        label="项目点名称"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('name')"
        prop="name"
        min-width="90px"
        label="姓名"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('sex')"
        prop="sex"
        min-width="80px"
        label="性别"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('age')"
        prop="age"
        min-width="80px"
        label="年龄"
        align="center"
      >
        <template #default="{ row }">
          <span>{{ row.age == 0 ? "-" : row.age }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="filtrateList.includes('tel')"
        prop="tel"
        min-width="120px"
        label="联系电话"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('diagnostic')"
        prop="diagnostic"
        min-width="160px"
        label="诊断结论"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('isPositive')"
        prop="isPositive"
        min-width="160px"
        label="是否阳性"
        align="center"
      >
        <template #default="{ row }">
          <span>{{
            row.isPositive == "1" ? "阳性" : row.isPositive == "0" ? "阴性" : ""
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="filtrateList.includes('isInvalid')"
        prop="isInvalid"
        min-width="160px"
        label="是否有效"
        align="center"
      >
        <template #header>
          <el-popover
            placement="bottom-start"
            title="提示"
            :width="300"
            trigger="hover"
            content="“无效”表示扫查结果不合格，无法出具报告，需要重新扫查，请等待处理"
          >
            <template #reference>
              <span
                >是否有效<el-icon style="color: rgb(66, 206, 206)"
                  ><WarningFilled /></el-icon
              ></span>
            </template>
          </el-popover>
        </template>
        <template #default="{ row }">
          <span :style="{ color: row.isInvalid == '1' ? 'red' : '' }">{{
            row.isInvalid == 1 ? "无效" : "有效"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="filtrateList.includes('invalidReason')"
        prop="invalidReason"
        min-width="120px"
        label="无效原因"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('devname')"
        prop="devname"
        min-width="120px"
        label="设备名称"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('auditstatus')"
        prop="auditstatus"
        min-width="84px"
        label="报告状态"
        align="center"
      >
        <template #default="{ row }">
          <span>{{
            row.auditstatus == 11
              ? "发送成功"
              : row.auditstatus == 12
              ? "发送失败"
              : ""
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="filtrateList.includes('dicomurl')"
        prop="dicomurl"
        min-width="185px"
        label="常规报告"
        align="center"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <el-button
            type="primary"
            text="primary"
            @click="regularInfo(row)"
            :style="{
              color: (row.dwncnt == 0 || !row.dwncnt) ? ''
                    : '#24ae24',
            }"
            >{{ (row.dwncnt == 0 || !row.dwncnt) ? "下载" : "已下载" }}</el-button
          >
          <el-button
            type="primary"
            text="primary"
            @click="printInfo(row)"
            :style="{
              color: (row.prtcnt == 0 || !row.prtcnt) ? ''
                    : '#24ae24',
            }"
            >{{ (row.prtcnt == 0 || !row.prtcnt) ? "打印" : "已打印" }}</el-button
          >
        </template>
      </el-table-column>
      <!-- <el-table-column
        v-if="filtrateList.includes('dicomurl')"
        prop="dicomurl"
        min-width="120px"
        label="常规报告"
        align="center"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <span @click="regularInfo(row)" style="cursor: pointer"
            ><el-icon :style="{ color: row.pdfUrl ? '#409eff' : '' }"
              ><Document /></el-icon
          ></span>
        </template>
      </el-table-column> -->
      <el-table-column
        v-if="filtrateList.includes('checkTime')"
        min-width="160px"
        prop="checkTime1"
        label="检查时间"
        align="center"
      >
        <template #default="{ row }">
          <span>{{
            row.checkTime1 ? row.checkTime1 : "----/--/-- --:--:--"
          }}</span>
        </template>
      </el-table-column>

      <el-table-column
        v-if="filtrateList.includes('docname')"
        prop="docname"
        min-width="100px"
        label="检查医师"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('reportTime')"
        prop="reportTime1"
        min-width="160px"
        label="报告时间"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('reportDoctor')"
        prop="reportDocname"
        min-width="160px"
        label="报告医师"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('qualityTime')"
        prop="uploadTime1"
        min-width="160px"
        label="质控日期"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('medicalRecordID')"
        prop="medicalRecordID"
        min-width="170px"
        label="病历记录ID"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('devid')"
        prop="devid"
        min-width="120px"
        label="设备SN"
        align="center"
      />
      <el-table-column
        v-if="$store.getters.name == 'admin'"
        label="操作"
        align="center"
        min-width="90px"
      >
        <template #default="{ row }">
          <el-button
            type="primary"
            link
            @click="edit(row)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageList.current"
      v-model:page-size="pageList.size"
      :page-sizes="[20, 40, 60, 80]"
      small="small"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageList.total"
      class="pagination-css"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- <el-dialog
      title="常规报告"
      v-model="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <iframe id="iframePdf" :src="pdfInfo.pdfUrl + '#toolbar=0'" style="width: 100%; height: 600px"></iframe>
      <template #footer>
        <span class="dialog-footer">
          <el-button v-if="pdfInfo.operateType == '打印'" type="primary" @click="printPdf">打印</el-button>
          <el-button v-if="pdfInfo.operateType == '下载'" type="primary" @click="downloadPdf">下载PDF文件并关闭窗口</el-button>
        </span>
      </template>
    </el-dialog> -->
    <el-dialog
      title="常规报告"
      v-model="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="960px"
    >
      <div v-if="pdfInfo.operateType == '下载'" id="pdfArea">
        <div style="page-break-before: always; box-sizing: border-box; font-size: 12px; padding: 10px;">
          <div style="padding: 0 35px; box-sizing: border-box;">
            <div style="font-size: 30px; text-align: center;margin-top: 10px;margin-bottom: 30px; font-weight: bold;">颈动脉超声筛查评估报告</div>
            <div style="height: 1px; border-bottom: 1px solid #000; margin:10px 0;" />
            <div>
              <div style="display: flex; justify-content: space-around;margin-bottom: 20px;">
                <div style="width: 300px;">姓名：{{ pdfInfo.name }}</div>
                <div style="width: 300px;">性别：{{ pdfInfo.sex }}</div>
                <div style="width: 300px;">年龄：{{ pdfInfo.age }}岁</div>
              </div>
              <div style="display: flex; justify-content: space-around;">
                <div style="width: 300px;">患者ID：{{ pdfInfo.t_sn }}</div>
                <div style="width: 300px;">检查部位：{{ JSON.parse(pdfInfo.origjson).PartName }}</div>
                <div style="width: 300px;">检查时间：{{ pdfInfo.checkTime1 }}</div>
              </div>
            </div>
            <div style="height: 1px; background: #000; margin:20px 0 0 0;" />
            <div style="display: flex; justify-content: space-between; height: 340px; margin: 20px 0;">
              <div style="width: 48%;">
                <img :src="pdfInfo.screenshot1Url" alt="" style="width: 100%; height: 100%;">
              </div>
              <div style="width: 48%;">
                <img :src="pdfInfo.screenshot2Url" alt="" style="width: 100%; height: 100%;">
              </div>
            </div>
            <div style="height: 1px; background: #000; margin:10px 0 20px 0;" />
            <div style="margin-top: 10px; height: 208px;">
              <span style="display: inline-block;font-size: 24px;line-height: 24px;font-weight: 600;margin-bottom: 5px;">超声提示：</span>
              <div v-for="(item, index) in pdfInfo.indication" :key="index" style="font-size: 14px;">{{ item }}</div>
            </div>
            <div style="color: #c45656; height: 340px;">
              <div style="font-size: 14px;">注：多发斑块时测量数据为较大者</div>
            </div>
            <div style="display: flex; justify-content: space-around;">
              <!-- <div style="width: 300px;">报告时间：{{ pdfInfo.reportTime1 }}</div>
              <div style="width: 300px;">检查医师：{{ pdfInfo.docname }}</div>
              <div style="width: 300px;">报告医师：{{ pdfInfo.reportDocname }}</div> -->
            </div>
            <div style="height: 1px; border-bottom: 1px solid #000; margin:10px 0;" />
            <div style="font-size: 12px; color: #666;line-height: 16px;">告知:1、超声检查准确性受诸多因素影响,如患者自身因素(肥胖、气体干扰、准备不充分、不能配合、病变位置特殊疾病所处不同阶段),设备因素(仪器型号及性能不同,其图像,质量和分辨率有差异)、检查者因素(超声结论是以国内外公认的影像特征为依据,不同检查者对超声影像的判读可能存在差异)等,此报告是影像检查结果,请以病理诊断或临床最后诊断为准,与本次检查相关的医疗活动应充分了解上述因素并与临床医生沟通。2、本报告仅作参考不作为证明或诊断材料。3、本报告仅对本次检查数据有效。</div>
          </div>
        </div>
        <div style="page-break-before: always; box-sizing: border-box; padding: 10px;">
          <img src="@/images/report2.png" alt="" srcset="" style="width: 100%; height: 100%;">
        </div>
        <div style="page-break-before: always; box-sizing: border-box; padding: 10px;">
          <img src="@/images/report3.png" alt="" srcset="" style="width: 100%; height: 100%;">
        </div>
      </div>
      <div v-if="pdfInfo.operateType == '打印'" id="routineArea">
        <div style="page-break-before: always; box-sizing: border-box; font-size: 12px;">
          <div style="padding: 20px; box-sizing: border-box;">
            <!-- <div style="font-size: 24px; text-align: center; color: #13227a;">{{ pdfInfo.insname }}</div> -->
            <div style="font-size: 30px; text-align: center;margin-top: 10px;margin-bottom: 30px; font-weight: bold;">颈动脉超声筛查评估报告</div>
            <div style="height: 1px; border-bottom: 1px solid #000; margin:10px 0;" />
            <div>
              <div style="display: flex; justify-content: space-around;margin-bottom: 20px;">
                <div style="width: 300px;">姓名：{{ pdfInfo.name }}</div>
                <div style="width: 300px;">性别：{{ pdfInfo.sex }}</div>
                <div style="width: 300px;">年龄：{{ pdfInfo.age }}岁</div>
              </div>
              <div style="display: flex; justify-content: space-around;">
                <div style="width: 300px;">患者ID：{{ pdfInfo.t_sn }}</div>
                <div style="width: 300px;">检查部位：{{ JSON.parse(pdfInfo.origjson).PartName }}</div>
                <div style="width: 300px;">检查时间：{{ pdfInfo.checkTime1 }}</div>
              </div>
            </div>
            <div style="height: 1px; border-bottom: 1px solid #000; margin:10px 0;" />
            <div style="display: flex; justify-content: space-between; height: 240px; margin: 20px 0;">
              <div style="width: 48%;">
                <img :src="pdfInfo.screenshot1Url" alt="" style="width: 100%; height: 100%;">
              </div>
              <div style="width: 48%;">
                <img :src="pdfInfo.screenshot2Url" alt="" style="width: 100%; height: 100%;">
              </div>
            </div>
            <div style="height: 1px; border-bottom: 1px solid #000; margin:10px 0;" />
            <div style="margin-top: 10px; margin-bottom: 120px;">
              <span style="display: inline-block;font-size: 24px;line-height: 24px;font-weight: 600;margin-bottom: 5px;">超声提示：</span>
              <div v-for="(item, index) in pdfInfo.indication" :key="index" style="font-size: 14px;">{{ item }}</div>
            </div>
            <div style="color: #c45656; margin-bottom: 240px;">
              <div style="font-size: 14px;">注：多发斑块时测量数据为较大者</div>
            </div>
            <div style="display: flex; justify-content: space-around;">
              <!-- <div style="width: 300px;">报告时间：{{ pdfInfo.reportTime1 }}</div>
              <div style="width: 300px;">检查医师：{{ pdfInfo.docname }}</div>
              <div style="width: 300px;">报告医师：{{ pdfInfo.reportDocname }}</div> -->
            </div>
            <div style="height: 1px; border-bottom: 1px solid #000; margin:10px 0;" />
            <div style="font-size: 12px; color: #666;line-height: 16px;">告知:1、超声检查准确性受诸多因素影响,如患者自身因素(肥胖、气体干扰、准备不充分、不能配合、病变位置特殊疾病所处不同阶段),设备因素(仪器型号及性能不同,其图像,质量和分辨率有差异)、检查者因素(超声结论是以国内外公认的影像特征为依据,不同检查者对超声影像的判读可能存在差异)等,此报告是影像检查结果,请以病理诊断或临床最后诊断为准,与本次检查相关的医疗活动应充分了解上述因素并与临床医生沟通。2、本报告仅作参考不作为证明或诊断材料。3、本报告仅对本次检查数据有效。</div>

          </div>
        </div>
        <div style="page-break-before: always; box-sizing: border-box; padding: 5px;">
          <img src="@/images/report2.png" alt="" srcset="" style="width: 100%; height: 100%;">
        </div>
        <div style="page-break-before: always; box-sizing: border-box; padding: 5px;">
          <img src="@/images/report3.png" alt="" srcset="" style="width: 100%; height: 100%;">
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button v-print="routinePrint" v-if="pdfInfo.operateType == '打印'" type="primary">打印</el-button>
          <el-button v-if="pdfInfo.operateType == '下载'" type="primary" @click="downloadPdf">下载PDF文件并关闭窗口</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="infoVisible"
      width="800px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      class="info"
    >
      <template #title>
        <span>{{ "患者信息" }}</span>
      </template>
      <el-form inline label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="条码：">
              <el-input v-model="patientForm.t_sn" disabled placeholder="请输入" style="width: 200px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构名称：">
              <el-select v-model="patientForm.insname" filterable placeholder="" style="width: 200px;">
                <el-option v-for="(item, index) in organNameList" :key="index" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名：">
              <el-input v-model="patientForm.name" placeholder="请输入" style="width: 200px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别：">
              <el-select v-model="patientForm.sex" placeholder="" style="width: 200px;">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="年龄：">
              <el-input v-model="patientForm.age" placeholder="请输入" style="width: 200px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检查医师：">
              <el-input v-model="patientForm.docname" placeholder="请输入" style="width: 200px;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系方式：">
              <el-input v-model="patientForm.tel" placeholder="请输入" style="width: 200px;" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submit">确定</el-button>
          <el-button @click="infoVisible = false">取消</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getUltraSoundList } from "@/apis/reportReview";
import format from "@/utils/format";
import { ElMessage } from "element-plus";
import JSZip from "jszip";
import { saveAs } from 'file-saver';
import { prtsn } from "@/apis/user";
import ExportSavePdf from "@/utils/canvasToPdf";
import { updateUltraIns } from "@/apis/reportList";
import { getAllSubIns } from "@/apis/hospitalManagement";
import { getUserOrganNameList } from "@/apis/reportStatistics";
export default {
  data() {
    let _this = this
    let nowTime = new Date().getTime();
    let stime = format(nowTime, "YYYY-MM-DD") + " " + "23:59:59";
    let etime = format(nowTime, "YYYY-MM-DD") + " " + "00:00:00";
    return {
      infoVisible: false,
      patientForm: null,
      organNameList: [],
      projectList: [],
      insnameProps: {
        lazy: true,
        checkStrictly: true,
        label: "insname",
        value: "inscode",
        lazyLoad(node, resolve) {
          _this.getJunior(node, resolve);
        },
      },
      routinePrint: {
        id: 'routineArea',
        popTitle: '打印', // 页眉
        extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签,使用逗号分隔
        preview: '', // 是否启动预览模式，默认是false（开启预览模式，可以先预览后打印）
        previewTitle: '', // 打印预览的标题（开启预览模式后出现）,
        previewPrintBtnLabel: '', // 打印预览的标题的下方按钮文本，点击可进入打印（开启预览模式后出现）
        zIndex: '', // 预览的窗口的z-index，默认是 20002（此值要高一些，这涉及到预览模式是否显示在最上面）
        previewBeforeOpenCallback() {}, // 预览窗口打开之前的callback（开启预览模式调用）
        previewOpenCallback() {}, // 预览窗口打开之后的callback（开启预览模式调用）
        beforeOpenCallback() {}, // 开启打印前的回调事件
        openCallback() {}, // 调用打印之后的回调事件
        closeCallback() {
          _this.isPrint()
          _this.dialogVisible = false
        }, // 关闭打印的回调事件（无法确定点击的是确认还是取消）
        url: '',
        standard: '',
        extraCss: ''
      },
      selectedItems: [], // 保存用户勾选的项目 9月25
      progress: 0, // 下载进度9月25
      progressVisible: false, // 进度条是否可见9月25
      progressStatus: "success", // 进度条状态9月25
      roleInfo: "",
      fullscreenLoading: false,
      json_fields: {
        序号: {
          field: "index",
          callback: (value) => {
            return String(value);
          },
        },
        条码: {
          field: "t_sn",
          callback: (value) => {
            return String(value);
          },
        },
        项目点名称: {
          field: "insname",
          callback: (value) => {
            return String(value);
          },
        },
        姓名: {
          field: "name",
          callback: (value) => {
            return String(value);
          },
        },
        性别: {
          field: "sex",
          callback: (value) => {
            return String(value);
          },
        },
        年龄: {
          field: "age",
          callback: (value) => {
            return String(value);
          },
        },
        联系电话: {
          field: "tel",
          callback: (value) => {
            return String(value);
          },
        },
        诊断结论: {
          field: "diagnostic",
          callback: (value) => {
            return String(value);
          },
        },
        是否阳性: {
          field: "isPositiveText",
          callback: (value) => {
            return String(value);
          },
        },
        是否有效: {
          field: "isInvalidText",
          callback: (value) => {
            return String(value);
          },
        },
        无效原因: {
          field: "invalidReason",
          callback: (value) => {
            return String(value);
          },
        },

        设备名称: {
          field: "devname",
          callback: (value) => {
            return String(value);
          },
        },
        报告状态: {
          field: "auditText",
          callback: (value) => {
            return String(value);
          },
        },

        检查时间: {
          field: "checkTime1",
          callback: (value) => {
            return String(value);
          },
        },

        检查医师: {
          field: "docname",
          callback: (value) => {
            return String(value);
          },
        },
        报告时间: {
          field: "reportTime1",
          callback: (value) => {
            return String(value);
          },
        },
        报告医师: {
          field: "reportDoctor",
          callback: (value) => {
            return String(value);
          },
        },
        质控日期: {
          field: "uploadTime1",
          callback: (value) => {
            return String(value);
          },
        },
        病历记录ID: {
          field: "medicalRecordID",
          callback: (value) => {
            return String(value);
          },
        },
        设备SN: {
          field: "devid",
          callback: (value) => {
            return String(value);
          },
        },
      },
      userExcelName: "",
      dialogVisible: false,
      pdfInfo: null,
      formInline: {
        keyword: "",
        inspectionTime: [stime, etime],
        reportTime: [],
        qualityTime: [],
        projectName: "",
        inspectDoctor: "",
        reportDoctor: "",
        reportStatus: "",
        isInvalid: "",
        diagnosis: "",
        isPositive: "",
      },
      filtrateList: [
        "devid",
        "devname",
        "name",
        "sex",
        "age",
        "tel",
        "checkTime",
        "insname",
        "docname",
        "reportTime",
        "reportDoctor",
        "qualityTime",
        "medicalRecordID",
        "diagnostic",
        "isPositive",
        "isInvalid",
        "invalidReason",
        "auditstatus",
        "dicomurl",
      ],
      tableData: [],
      selectedItems: [], // 保存用户勾选的项目
      downloadedFiles: [], // 已经下载成功的文件名列表
      tableLoading: false,
      selectedRows: [], // 选中的行数据9月25号
      pageList: {
        current: 1,
        size: 20,
        total: 0,
      },
      statusList: [
        {
          label: "发送失败",
          value: "12",
        },
        {
          label: "发送成功",
          value: "11",
        },
      ],
      isUsedList: [
        {
          label: "无效",
          value: "1",
        },
        {
          label: "有效",
          value: "0",
        },
      ],
      isPositiveList: [
        {
          label: "阳性",
          value: "1",
        },
        {
          label: "阴性",
          value: "0",
        },
      ],
    };
  },
  mounted() {
    this.getUserOrganName()
    this.getTableData();//9月25号增加的这行
    let hncyPoint = localStorage.getItem("hncyPoint");
    if (hncyPoint) {
      this.filtrateList = JSON.parse(hncyPoint);
    }
    this.init();
    this.saveCookie();
    this.getJunior()
    this.roleInfo = this.$store.getters.role ? this.$store.getters.role : "";
    this.getTableData(); // 初始化加载表格数据10月20号
    this.loadDownloadedFiles(); // 加载已下载的文件列表10月20号
  },
  methods: {
    getUserOrganName() {
      this.organNameList = []
      getUserOrganNameList({
        uname: this.$store.getters.name,
      }).then((result) => {
        this.organNameList = result.data;
      });
    },
    getJunior() {
      this.projectList = []
      getAllSubIns({
        uname: this.$store.getters.name,
        inscode: this.$store.getters.inscode,
        subins: '',
      }).then((res) => {
        if (res.code == 0) {
          if (res.data && res.data.length > 0) {
            this.projectList = res.data
          }
        }
      });
    },
    edit(row) {
      this.patientForm = row
      console.log(row, 'row')
      console.log(this.patientForm, 'patientForm')
      this.infoVisible = true
    },
    submit() {
      console.log(this.patientForm, 'this.patientForm')
      let hospitalInfo = []
      if (this.patientForm.insname) {
        hospitalInfo = this.projectList.filter(item => {
          return item.insname == this.patientForm.insname
        })
      }
      if (hospitalInfo.length > 0) {
        this.patientForm.inscode = hospitalInfo[0].inscode
      }
      updateUltraIns({
        uname: this.$store.getters.rname,
        inscode: this.$store.getters.inscode,
        data: JSON.stringify(this.patientForm),
      }).then(res => {
        if (res.code == 0) {
          ElMessage({
            message: '编辑成功！',
            type: 'success',
          });
          this.getTableData()
        } else {
          ElMessage({
            message: res.error,
            type: 'error',
          });
        }
        this.infoVisible = false
      })
    },
    downloadPdf() {
      let loadName = (this.pdfInfo.name ? (this.pdfInfo.name + '_') : '') + (this.pdfInfo.age ? (this.pdfInfo.age + '_') : '') + (this.pdfInfo.t_sn ? this.pdfInfo.t_sn : '')
      ExportSavePdf("pdfArea", loadName, "");
      this.dialogVisible = false
      this.isDwn()
      // let link = document.createElement('a')
      // let _this = this
      // this.fetchPDFThroughProxy(this.pdfInfo.pdfUrl).then(blob => {
      //   link.href = URL.createObjectURL(blob)
      //   link.download = (this.pdfInfo.name ? (this.pdfInfo.name + '_') : '') + (this.pdfInfo.age ? (this.pdfInfo.age + '_') : '') + (this.pdfInfo.t_sn ? this.pdfInfo.t_sn : '')
      //   document.body.appendChild(link)
      //   link.click()
      //   document.body.removeChild(link)
      //   this.dialogVisible = false
      //   _this.isDwn()
      // })
    },
    printPdf() {
      let link = document.createElement('iframe')
      let _this = this
      this.fetchPDFThroughProxy(this.pdfInfo.pdfUrl).then(blob => {
        link.style.display = 'none'
        let idNum = 'printPdf' + new Date().getTime()
        link.setAttribute('id', idNum)
        link.src = URL.createObjectURL(blob)
        document.body.appendChild(link)
        let iframePdf = document.getElementById(idNum).contentWindow
        iframePdf.print()
        window.URL.revokeObjectURL(link.src)
        this.dialogVisible = false
        this.isPrint()
      })
    },
    isPrint() {
      prtsn({
        type: "ultrasound",
        action: "print",
        sn: this.pdfInfo.t_sn,
        uname: this.$store.getters.name,
      }).then((res) => {
        if (res.data.status == "00") {
          this.getTableData();
        }
      });
    },
    isDwn() {
      prtsn({
        type: "ultrasound",
        action: "download",
        sn: this.pdfInfo.t_sn,
        uname: this.$store.getters.name,
      }).then((res) => {
        if (res.data.status == "00") {
          this.getTableData();
        }
      });
    },
    // 通过代理下载 PDF 文件
    fetchPDFThroughProxy(url) {
      const baseURL = "http://cvd.cdhyhs.com/pdf/";
      const cleanUrl = url.replace("https://ultrasound.cdhyhs.com/", "");
        // const proxyUrl = baseURL + cleanUrl;
        const proxyUrl = url;

      return fetch(proxyUrl)
        .then((response) => {
          if (!response.ok) {
            throw new Error("Network response was not ok");
          }
          return response.blob();
        })
        .catch((error) => {
          console.error("Error fetching PDF:", error);
          throw error;
        });
    },
    // 检查报告时间是否已选择
  isReportTimeSelected() {
    return (
      this.formInline.reportTime &&
      this.formInline.reportTime.length > 0 &&
      this.formInline.reportTime[0] &&
      this.formInline.reportTime[1]
    );
  },
    saveCookie() {
      let hncyPoint = JSON.stringify(this.filtrateList);
      localStorage.setItem("hncyPoint", hncyPoint);
    },
    changeBox() {
      let hncyPoint = JSON.stringify(this.filtrateList);
      localStorage.setItem("hncyPoint", hncyPoint);
    },
    async downloadEx() {
      let insTitle = this.$store.getters.insname
        ? this.$store.getters.insname
        : "";
      let inspecSTime = "";
      let inspecETime = "";
      let data = [];
      this.fullscreenLoading = true;
      if (
        this.formInline.inspectionTime &&
        this.formInline.inspectionTime.length > 0
      ) {
        inspecSTime = this.formInline.inspectionTime[0];
        inspecETime = this.formInline.inspectionTime[1];
        this.userExcelName =
          insTitle + "_超声报告列表_" + inspecSTime + "~" + inspecETime;
        let res = await getUltraSoundList({
          page: 1, // 当前页
          size: 10000, // 每页size
          uname: this.$store.getters.name, // 登录用户
          insname: this.$store.getters.insname, //用户机构名
          keyword: this.formInline.keyword ? this.formInline.keyword : "", // 关键字
          inspectionStime: this.formInline.inspectionTime
            ? this.formInline.inspectionTime[0]
              ? this.formInline.inspectionTime[0]
              : ""
            : "", // 检查开始时间
          inspectionEtime: this.formInline.inspectionTime
            ? this.formInline.inspectionTime[1]
              ? this.formInline.inspectionTime[1]
              : ""
            : "", // 检查结束时间
          qualityStime: this.formInline.qualityTime
            ? this.formInline.qualityTime[0]
              ? this.formInline.qualityTime[0]
              : ""
            : "", //质控开始时间
          qualityEtime: this.formInline.qualityTime
            ? this.formInline.qualityTime[1]
              ? this.formInline.qualityTime[1]
              : ""
            : "", //质控结束时间
          reportStime: this.formInline.reportTime
            ? this.formInline.reportTime[0]
              ? this.formInline.reportTime[0]
              : ""
            : "", //报告开始时间
          reportEtime: this.formInline.reportTime
            ? this.formInline.reportTime[1]
              ? this.formInline.reportTime[1]
              : ""
            : "", //报告结束时间
          projectName: this.formInline.projectName
            ? this.formInline.projectName
            : "", //项目点名称

          inspectDoctor: this.formInline.inspectDoctor
            ? this.formInline.inspectDoctor
            : "", //检查医师
          reportDoctor: this.formInline.reportDoctor
            ? this.formInline.reportDoctor
            : "", //报告医师

          reportStatus: this.formInline.reportStatus
            ? this.formInline.reportStatus
            : "", //报告状态
          // isvalid: this.formInline.isUsed ? this.formInline.isUsed : "", // 是否有效
          project: "村医",
          isInvalid: this.formInline.isInvalid,
          diagnosis: this.formInline.diagnosis,
          isPositive: this.formInline.isPositive,
        });
        if (res.code == 0) {
          if (res.data && res.data.length > 0) {
            res.data.forEach((el, index) => {
              let auditText = "";
              el.index = index + 1;
              if (el.auditstatus == 11) {
                auditText = "发送成功";
              } else if (el.auditstatus == 12) {
                auditText = "发送失败";
              }
              el.isInvalidText = el.isInvalid == 0 ? "有效" : "无效";
              el.isPositiveText =
                el.isPositive == "1"
                  ? "阳性"
                  : el.isPositive == "0"
                  ? "阴性"
                  : "";

              el.auditText = auditText;
              if (el.checkTime > 0) {
                el.checkTime1 = format(
                  el.checkTime * 1000,
                  "YYYY-MM-DD HH:mm:ss"
                );
              } else {
                el.checkTime1 = "";
              }
              el.reportTime1 = format(
                el.reportTime * 1000,
                "YYYY-MM-DD HH:mm:ss"
              );
              el.uploadTime1 = format(
                el.uploadTime * 1000,
                "YYYY-MM-DD HH:mm:ss"
              );
              el.medicalRecordID = "";
              el.diagnostic = el.diagnosis ? el.diagnosis : "";
              if (el.json) {
                let jsonData = JSON.parse(el.json.replace(/'/g, '"'));
                el.medicalRecordID = jsonData
                  ? jsonData.mrid
                    ? jsonData.mrid
                    : el.c_sn
                  : el.c_sn;
                el.tel = jsonData ? (jsonData.tel ? jsonData.tel : "") : "";
              } else {
                el.medicalRecordID = el.c_sn ? el.c_sn : "";
              }
              // el.medicalRecordID = el.c_sn ? el.c_sn : ''
              // if (el.json) {
              //   jsonData = JSON.parse(el.json)
              //   el.tel = jsonData ? jsonData.tel ? jsonData.tel : '' : ''
              //   el.diagnostic = jsonData ? jsonData.diagnosis ? jsonData.diagnosis : '' : ''
              // }
            });
            data = res.data;
          }
        }
        this.fullscreenLoading = false;
        return data;
      } else {
        ElMessage({
          message: "请选择检查时间",
          type: "warning",
        });
        this.fullscreenLoading = false;
        return data;
      }
    },
    init() {
      this.getTableData();
    },
    regularInfo(row) {
      // if (row.auditstatus == 10) {
        console.log(row, "row");
        row.operateType = "下载";
        this.pdfInfo = {};
        this.pdfInfo = row;
        let indication = []
        if (row.vender == '非雀医疗') {
          indication = JSON.parse(row.origjson).Description.split('\n')
        } else if (row.vender == '飞依诺') {
          indication = JSON.parse(row.origjson).Summary.split('\r\n')
        }
        this.pdfInfo.indication = indication
        this.dialogVisible = true;
      // } else {
      //   ElMessage({
      //     type: "warning",
      //     message: "报告未审核，请等待审核通过后查看",
      //   });
      // }
    },
    printInfo(row) {
      // if (row.auditstatus == 10) {
        console.log(row, "row");
        row.operateType = "打印";
        this.pdfInfo = {};
        this.pdfInfo = row;
        let indication = []
        if (row.vender == '非雀医疗') {
          indication = JSON.parse(row.origjson).Description.split('\n')
        } else if (row.vender == '飞依诺') {
          indication = JSON.parse(row.origjson).Summary.split('\r\n')
        }
        this.pdfInfo.indication = indication
        this.dialogVisible = true;
      // } else {
      //   ElMessage({
      //     type: "warning",
      //     message: "报告未审核，请等待审核通过后查看",
      //   });
      // }
    },
    // regularInfo(row) {
    //   this.pdfInfo = ''
    //   if (row.pdfUrl) {
    //     this.pdfInfo = row
    //     this.dialogVisible = true;
    //   } else {
    //     ElMessage({
    //       message: "暂无报告",
    //       type: "warning",
    //     });
    //   }
    // },
    // getTableData() {
    //   this.tableLoading = true;
    //   this.tableData = [];
    async getTableData() {
      try {
        const res = await getUltraSoundList({ page: 1, size: 100 }); // 调用 API 获取 PDF 列表
        if (res.code === 0) {
        //   this.tableData = res.data.map((item) => ({
        //     name: item.projectName,  // 动态获取的项目名称
        //     pdfUrl: item.pdfUrl,     // 动态获取的 PDF URL
        //   }));
        // } 9月25号修改前的代码
        // 假设项目名称来自API返回的数据中的`projectName`
        this.projectName = res.data[0]?.projectName || '未知项目'; // 赋值给 projectName
          this.tableData = res.data.map((item) => ({
            name: item.name,  // 动态获取的姓名
            t_sn: item.t_sn,  // 动态获取的条码
            pdfUrl: item.pdfUrl,     // 动态获取的 PDF URL
          }));
        }
      } catch (error) {
        console.error("获取表格数据失败", error);
        this.$message.error("获取表格数据失败，请稍后重试");
      }
      getUltraSoundList({
        page: this.pageList.current, // 当前页
        size: this.pageList.size, // 每页size
        uname: this.$store.getters.name, // 登录用户
        insname: this.$store.getters.insname, //用户机构名
        keyword: this.formInline.keyword ? this.formInline.keyword : "", // 关键字
        inspectionStime: this.formInline.inspectionTime
          ? this.formInline.inspectionTime[0]
            ? this.formInline.inspectionTime[0]
            : ""
          : "", // 检查开始时间
        inspectionEtime: this.formInline.inspectionTime
          ? this.formInline.inspectionTime[1]
            ? this.formInline.inspectionTime[1]
            : ""
          : "", // 检查结束时间
        qualityStime: this.formInline.qualityTime
          ? this.formInline.qualityTime[0]
            ? this.formInline.qualityTime[0]
            : ""
          : "", //质控开始时间
        qualityEtime: this.formInline.qualityTime
          ? this.formInline.qualityTime[1]
            ? this.formInline.qualityTime[1]
            : ""
          : "", //质控结束时间
        reportStime: this.formInline.reportTime
          ? this.formInline.reportTime[0]
            ? this.formInline.reportTime[0]
            : ""
          : "", //报告开始时间
        reportEtime: this.formInline.reportTime
          ? this.formInline.reportTime[1]
            ? this.formInline.reportTime[1]
            : ""
          : "", //报告结束时间
        projectName: this.formInline.projectName
          ? this.formInline.projectName
          : "", //项目点名称

        inspectDoctor: this.formInline.inspectDoctor
          ? this.formInline.inspectDoctor
          : "", //检查医师
        reportDoctor: this.formInline.reportDoctor
          ? this.formInline.reportDoctor
          : "", //报告医师

        reportStatus: this.formInline.reportStatus
          ? this.formInline.reportStatus
          : "", //报告状态
        // isvalid: this.formInline.isUsed ? this.formInline.isUsed : "", // 是否有效
        project: "村医",
        isInvalid: this.formInline.isInvalid,
        diagnosis: this.formInline.diagnosis,
        isPositive: this.formInline.isPositive,
      }).then((res) => {
        if (res.code == 0) {
          this.tableData = res.data || [];
          this.pageList.total = res.size;
          if (res.data && res.data.length > 0) {
            res.data.forEach((el) => {
              el.isEdit = false
              el.checkTime1 = format(
                el.checkTime * 1000,
                "YYYY-MM-DD HH:mm:ss"
              );
              el.reportTime1 = format(
                el.reportTime * 1000,
                "YYYY-MM-DD HH:mm:ss"
              );
              el.uploadTime1 = format(
                el.uploadTime * 1000,
                "YYYY-MM-DD HH:mm:ss"
              );
              // if (el.json) {
              //   jsonData = JSON.parse(el.json)
              //   el.medicalRecordID = jsonData ? jsonData.mrid ? jsonData.mrid : el.c_sn : el.c_sn
              //   el.tel = jsonData ? jsonData.tel ? jsonData.tel : '' : ''
              //   el.diagnostic = jsonData ? jsonData.diagnosis ? jsonData.diagnosis : '' : ''
              //   el.tel = jsonData ? jsonData.tel ? jsonData.tel : '' : ''
              // }
              el.diagnostic = el.diagnosis ? el.diagnosis : "";
              el.medicalRecordID = "";
              if (el.json) {
                let jsonData = JSON.parse(el.json.replace(/'/g, '"'));
                el.medicalRecordID = jsonData
                  ? jsonData.mrid
                    ? jsonData.mrid
                    : el.c_sn
                  : el.c_sn;
              } else {
                el.medicalRecordID = el.c_sn ? el.c_sn : "";
              }
            });
            this.tableData = res.data;
          }
          this.pageList.total = res.size;
          this.tableLoading = false;
        }
      });
    },
    // 搜索
    search() {
      this.pageList.current = 1;
      this.getTableData();
    },
    // 重置
    reset() {
      let nowTime = new Date().getTime();
      let stime = format(nowTime, "YYYY-MM-DD") + " " + "23:59:59";
      let etime = format(nowTime, "YYYY-MM-DD") + " " + "00:00:00";
      this.pageList.current = 1;
      this.formInline.keyword = "";
      this.formInline.inspectionTime = [stime, etime];
      this.formInline.reportTime = [];
      this.formInline.qualityTime = [];
      this.formInline.projectName = "";
      this.formInline.inspectDoctor = "";
      this.formInline.isInvalid = "";
      this.formInline.diagnosis = "";
      this.formInline.isPositive = "";
      this.formInline.reportDoctor = "";
      this.formInline.reportStatus = "";
      this.formInline.isUsed = "";
      this.init();
      //9月25号增加下面2行
      this.pageList.current = 1;
      this.getTableData();
    },
    handleSizeChange(val) {
      this.pageList.current = 1;
      this.pageList.size = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.pageList.current = val;
      this.getTableData();
    },
// ---------------- 通用的 PDF 下载和导出逻辑 ----------------10月20号
// ---------------- 加载和保存已下载文件的逻辑 ----------------
loadDownloadedFiles() {
      // 从 localStorage 加载已下载的文件列表
      const downloaded = localStorage.getItem('downloadedFiles');
      if (downloaded) {
        this.downloadedFiles = JSON.parse(downloaded);
      }
    },

    saveDownloadedFiles() {
      // 保存下载成功的文件列表到 localStorage
      localStorage.setItem('downloadedFiles', JSON.stringify(this.downloadedFiles));
    },
// 处理用户勾选的项目
    handleSelectionChange(val) {
      this.selectedItems = val;
    },
async downloadAndExportPDFs(items) {
      const zip = new JSZip();
      const validItems = items.filter((item) => item.isInvalid === "0");
      if (validItems.length === 0) {
        this.$message.warning("没有有效报告可供下载");
        return;
      }

      this.progress = 0;
      this.progressVisible = true;
      this.progressStatus = "active";

      const downloadPromises = validItems.map((item, index) => {
        const pdfFileName = `${item.name}_${item.t_sn}.pdf`;
        return this.fetchPDFThroughProxy(item.pdfUrl)
          .then((pdfBlob) => {
            if (pdfBlob) {
              zip.file(pdfFileName, pdfBlob);
            }
            // 更新进度条
            this.progress = Math.floor(((index + 1) / validItems.length) * 100);
          })
          .catch((error) => {
            console.error(`Failed to download ${pdfFileName}:`, error);
          });
      });

      try {
        await Promise.all(downloadPromises);
        if (zip.files.length === 0) {
          this.$message.warning("没有有效报告可供下载");
          this.progressVisible = false;
          return;
        }

        const currentDate = format(new Date(), "YYYY-MM-DD");
        const zipFileName = `村医超声报告_${validItems.length}份_${currentDate}.zip`;

        zip.generateAsync({ type: "blob" }).then((blob) => {
          saveAs(blob, zipFileName);
          this.progressVisible = false;
        });
      } catch (error) {
        console.error("批量导出失败", error);
        this.$message.error("导出过程中出错，请稍后重试");
        this.progressStatus = "exception";
      }
    },

    // 通过代理下载 PDF 文件
    // fetchPDFThroughProxy(url) {
    //   const baseURL = "http://cvd.cdhyhs.com/pdf/";
    //   const cleanUrl = url.replace("https://ultrasound.cdhyhs.com/", "");
    //   const proxyUrl = baseURL + cleanUrl;

    //   return fetch(proxyUrl)
    //     .then((response) => {
    //       if (!response.ok) {
    //         throw new Error("Network response was not ok");
    //       }
    //       return response.blob();
    //     })
    //     .catch((error) => {
    //       console.error("Error fetching PDF:", error);
    //       throw error;
    //     });
    // },

    // ---------------- 已选定项目的导出 ----------------
    exportSelectedPDFs() {
      if (this.selectedItems.length === 0) {
        this.$message.warning("请先选择要导出的报告");
        return;
      }
      this.downloadAndExportPDFs(this.selectedItems);
    },

    // ---------------- 批量导出所有报告的功能 ----------------
    async exportAllPDFs() {
      // 检查是否选择了报告时间
    if (!this.isReportTimeSelected()) {
      this.$message.warning("未选择报告时间，请选择时间后再尝试导出");
      return; // 停止导出操作
    }
      this.progressVisible = true; // 显示进度条
      let allItems = [];

      const pageSize = 100; // 每页请求的数据数量
      let currentPage = 1;
      let totalPages = 1;

      try {
        // 获取第一页数据并确定总页数
        const firstPage = await this.getUltraSoundData(currentPage, pageSize);
        allItems.push(...firstPage.data);
        totalPages = Math.ceil(firstPage.total / pageSize);

        // 获取其余页的数据
        while (currentPage < totalPages) {
          currentPage++;
          const pageData = await this.getUltraSoundData(currentPage, pageSize);
          allItems.push(...pageData.data);

          // 更新进度条
          this.progress = Math.floor((currentPage / totalPages) * 100);
        }

        // 导出所有数据
        this.downloadAndExportPDFs(allItems);
      } catch (error) {
        console.error("获取所有报告数据时出错:", error);
        this.$message.error("批量导出失败");
        this.progressStatus = "exception";
      }
    },

    // 获取每页的超声报告数据
    async getUltraSoundData(page, size) {
      const res = await getUltraSoundList({
        page: page,
        size: size,
        uname: this.$store.getters.name,
        insname: this.$store.getters.insname,
        reportStime: this.formInline.reportTime[0],
        reportEtime: this.formInline.reportTime[1],
        projectName: this.formInline.projectName,
        inspectDoctor: this.formInline.inspectDoctor,
        reportDoctor: this.formInline.reportDoctor,
        reportStatus: this.formInline.reportStatus,
        project: "村医",
      });

      if (res.code === 0) {
        return res;
      } else {
        throw new Error("获取数据失败");
      }
    },
  },
  // },
};
</script>